<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>01-05 reduce - 二次归类</title>
</head>

<body>
  <h1>二次归类</h1>
  年份相同的，放到一个新数组中
  <script>
    const arr = [{
      year: '2021',
      name: '张三'
    }, {
      year: '2020',
      name: '李四'
    }, {
      year: '2021',
      name: '王五'
    }, {
      year: '2022',
      name: '赵六'
    }]

    const maps = {}
    arr.forEach(item => {
      const year = item.year
      if (maps[year]) {
        maps[year].push(item)
      } else {
        maps[year] = [item]
      }
    })
    console.log('111 maps=', maps)

    //---------------------------------------------
    const maps2 = {}
    for (let i = 0; i < arr.length; i ++) {
      const item = arr[i]
      const year = item.year
      if (maps2[year]) {
        maps2[year].push(item)
      } else {
        maps2[year] = [item]
      }
    }
    console.log('222 maps2=', maps2)

    //---------------------------------------------
    const maps3 = arr.reduce((pre, cur) => {
      const key = cur.year; // -- 这里不可省略 ；冒号
      (pre[key] || (pre[key] = [])).push(cur)
      return pre
    }, [])
    console.log('333 maps3=', maps3)
  </script>
</body>

</html>